package cn.pomelo;

import com.csvreader.CsvWriter;
import com.mysql.cj.jdbc.ClientPreparedStatement;
import com.mysql.cj.jdbc.JdbcStatement;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

public class CSVFileUtil {

    /**
     * 将txt文件读到 csv文件中
     * @return
     * @throws IOException
     */
    public static long readToCSV() throws IOException {
        File file = new File(Constant.BASE_DATA_LOCATION);
        long total = 0;
        File[] files = file.listFiles((f) -> {
            return f.getName().endsWith(".txt");
        });
        File temp = new File(Constant.CSV_DATA_LOCATION);
        if (!temp.exists()) {
            temp.mkdirs();
        }
        CsvWriter csvWriter = new CsvWriter(Constant.CSV_DATA_LOCATION + "/all" + ".csv", ',', StandardCharsets.UTF_8);
        for (File f : Objects.requireNonNull(files)) {
            // txt文本是ANSI编码
            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(f), "GBK"));
            String s = reader.readLine();
            String[] strings = {s.substring(0, 6), s.substring(6, s.indexOf("日线")).trim()};
            s = reader.readLine(); // 跳过第二行
            while (!Constant.END_LOGOTYPE.equals((s = reader.readLine()))) {
                List<String> l = new ArrayList<>(Arrays.asList(strings));
                String[] split = s.split(",");
                l.addAll(Arrays.asList(split));
                csvWriter.writeRecord(l.toArray(split));
                total++;
            }
            reader.close();
        }
        csvWriter.close();
        return total;
    }

    /**
     * 将csv 文件读到数据库
     *
     * @throws IOException
     */
    public static void fun1() throws IOException {
        Connection connection = null;
        Statement statement = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://data2.ycdlcd.com:3306/stock?allowLoadLocalInfile=true", "stock", "123456");
            String sql = "LOAD DATA LOCAL INFILE 'D:/tmp/test/all.csv' IGNORE INTO TABLE trade FIELDS TERMINATED BY ','";
            statement = connection.prepareStatement(sql);
            if (statement.isWrapperFor(JdbcStatement.class)) {
                ClientPreparedStatement mysqlStatement = statement.unwrap(ClientPreparedStatement.class);
                mysqlStatement.executeUpdate();
            }
        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e);
        } finally {
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    /**
     * 使用字符流读取文件
     *
     * @throws IOException
     */
    public static void csvRead() throws IOException {
        File file = new File(Constant.CSV_DATA_LOCATION + "/all.csv");
        System.out.println(file.length());
        BufferedReader bf = new BufferedReader(new FileReader(file));
        String line = bf.readLine();
//        System.out.println(line);
        while ((line = bf.readLine()) != null) {
//            System.out.println(line);
        }
    }

    /**
     * 使用字节流读到内存中
     *
     * @throws IOException
     */
    public static void read() throws IOException {
        FileInputStream in = new FileInputStream(Constant.CSV_DATA_LOCATION + "/all.csv");
        byte[] bytes = new byte[in.available()];
        System.out.println(in.available());
        in.read(bytes);
        // 输出数据
//        System.out.println(new String(bytes));
        in.close();
    }

    /**
     * 使用字节流读取
     * @return
     * @throws IOException
     */
    public static void readAll() throws IOException {
        File file = new File(Constant.BASE_DATA_LOCATION);
        long total = 0;
        File[] files = file.listFiles((f) -> {
            return f.getName().endsWith(".txt");
        });
        File temp = new File(Constant.CSV_DATA_LOCATION);
        if (!temp.exists()) {
            temp.mkdirs();
        }
        CsvWriter csvWriter = new CsvWriter(Constant.CSV_DATA_LOCATION + "/all" + ".csv", ',', StandardCharsets.UTF_8);
        for (File f : Objects.requireNonNull(files)) {
            BufferedInputStream in = new BufferedInputStream(new FileInputStream(f));
//            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(f), "GBK"));
//            String s = reader.readLine();
//            String[] strings = {s.substring(0, 6), s.substring(6, s.indexOf("日线")).trim()};
//            s = reader.readLine(); // 跳过第二行
//            while (!Constant.END_LOGOTYPE.equals((s = reader.readLine()))) {
//                List<String> l = new ArrayList<>(Arrays.asList(strings));
//                String[] split = s.split("\t");
//                l.addAll(Arrays.asList(split));
//                csvWriter.writeRecord(l.toArray(split));
//                total++;
//            }
//            in.read
//            byte[] bytes = new byte[in.available()];
//            in.read(bytes);
//            csvWriter.write(new String(bytes), true);
//            in.close();
        }
        csvWriter.close();
    }

}
